<template>
  <div class="AMap">
    <div class="amap-detail">
      <!-- 工单列表 -->
      <div
        class="left-body"
        :style="{width: isShowLeft ? '220px' : '0px'}">
        <div
          class="left-show-btn left-position"
          @click="isShowLeft = !isShowLeft">
          <i size="16" :class="isShowLeft ? 'el-icon-arrow-left' : 'el-icon-arrow-right'"/>
        </div>
        <div class="amap-list-body">
          <el-tabs v-model="activeName" @tab-click="handleClick" style="padding-left: 10px">
            <el-tab-pane label="实时监控" name="first">
              <el-table
                ref="multipleTable"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @select="onTableSelect"
                @select-all="handleSelectionChange">
                <el-table-column
                  type="selection">
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="姓名">
                </el-table-column>
                <el-table-column
                  prop="state"
                  label="状态"
                  show-overflow-tooltip>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="实时告警" name="second">实时告警</el-tab-pane>
          </el-tabs>
        </div>

      </div>
      <div id="container" class="mymap" />
      <div class="input-card" style="width:14rem">
        <div class="input-item">
          <img src="~@/assets/erwei.png" style="cursor:pointer;" @click="loadErMap()">
          <img src="~@/assets/weixin.png" style="cursor:pointer;" @click="loadWeiMap()">
        </div>
        <div class="input-item">
          <button @click="addd">click</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import AMap from 'AMap'

  let marker = {}
  let placeSearch = {}
  let geocoder = {}
  let satelliteLayer = {}
  let overlayGroups={}
  let markers=[]
  let markerMap = new Map()
  let remoeMarkerMap = new Map()
  export default {
    name: "Gmap",
    data() {
      return {
        tableData: [{
          id:1,
          name: '王小虎',
          position: [118.180987, 24.483432],
          state: '在线'
        }, {
          id:2,
          name: '王大虎',
          position: [118.160987, 24.485432],
          state: '在线'
        }, {
          id:3,
          name: '刘小虎',
          position: [118.180387, 24.486432],
          state: '离线'
        }, {
          id:4,
          name: '张小虎',
          position: [118.182987, 24.484432],
          state: '在线'
        }, {
          id:5,
          name: '徐小虎',
          position: [118.170987, 24.484432],
          state: '离线'
        }, {
          id:6,
          name: '周小虎',
          position: [118.180947, 24.483422],
          state: '离线'
        }, {
          id:7,
          name: '陈小虎',
          position: [118.185987, 24.481432],
          state: '离线'
        }],
        multipleSelection: [],
        activeName: 'first',
        activeIndex: '1',
        orderList: [],  // 工单列表
        orderCount: 0,
        orderPage: 0,
        amapOrderList: [],  // 地图显示工单列表
        amapServiceList: [],
        isShowLeft: true,
        isShowRight: true,
        serviceMarker: {},
        orderMarker: {},
        selectOrder: [],  // 选中工单列表
        serviceList: [], // 人员列表
        serviceCount: 0,
        servicePage: 0,
        selectService: {},  // 选中服务人员
        selectCooperation: [],  // 选中协同人列表
        isShowModal: this.value,
        madalLoading: true,
        center: [118.180987, 24.486432],
        cityList: [],
        selectCity: '',
        isClickMap: false,
        routerLink: '',
        startInterval: '',
        selectIndex: ''
      }
    },
    mounted () {
      this.loadmap()   // 加载地图和相关组件
      //this.getOrderList()
    },
    watch: {

    },
    created () {

    },
    methods: {
      loadmap () {
        map = new AMap.Map('container', {
          resizeEnable: true,
          center: this.center,
          zoom: 13
        })
        let _this = this
        // 构造官方卫星、路网图层
        satelliteLayer = new AMap.TileLayer.Satellite();
        let roadNetLayer =  new AMap.TileLayer.RoadNet();
        map.add([roadNetLayer]);
        AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Geocoder', 'AMap.InfoWindow'], () => {
          map.addControl(new AMap.ToolBar())
          map.addControl(new AMap.Scale())
        })
        marker = new AMap.Marker({
          icon: '/static/img/iconicon1.png',
          position: this.center
          // title: provinces[i].name
        })
        AMap.service('AMap.Geocoder', () => {
          // 实例化Geocoder
          geocoder = new AMap.Geocoder({
            city: '010' // 城市，默认：“全国”
          })
        })
        placeSearch = new AMap.PlaceSearch({ // 构造地点查询类
          // pageSize: 5,
          // pageIndex: 1,
          city: '010' // 城市
          // map: map
          // panel: 'panel'
        })
        marker.setMap(map)
        map.on('click', (e) => {
          console.log('您在[ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ]的位置点击了地图！')
          this.center = [e.lnglat.getLng(), e.lnglat.getLat()]
          marker.setPosition(this.center)
          map.panTo(this.center)
          // map.setFitView()
          _this.getNowAddress()
        })
        // 点击marker事件
        AMap.event.addListener(marker, 'click', () => {
          _this.getNowAddress()
        })
        // 监听点击搜索结果标签事件
        AMap.event.addListener(placeSearch, 'markerClick', (e) => {
          console.log(e)
          this.center = [e.data.location.lng, e.data.location.lat]
          marker.setPosition(this.center)
          map.panTo(this.center)
          _this.getNowAddress()
        })
        // 输入提示
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      checkbox_select(row){
        console.log(row)
      },
      handleSelectionChange(val) {
        console.log(val)
        if(val.length>0) {
          this.addMarkers(val)
        }else{
          markerMap.clear()
          map.clearMap();
        }
      },
      onTableSelect(rows, row) {
        let selected = rows.length && rows.indexOf(row) !== -1
        if(selected){
          let lnglat = row.position
          let marker = new AMap.Marker({
            map: map,
            position: new AMap.LngLat(lnglat[0], lnglat[1]),
          });
          markerMap.set(row.id,marker)
        }else{
          console.log(row.id)
          let lnglat = row.position
          let marker = markerMap.get(row.id)
          console.log(marker)
          marker.hide()
          markerMap.delete(row.id)
        }
        console.log(markerMap)
      },
      addMarkers(val){
        for(var v of val){
          // 创建点实例
          let lnglat = v.position
          var marker = new AMap.Marker({
            map: map,
            position: new AMap.LngLat(lnglat[0], lnglat[1]),
          });
          markerMap.set(v.id, marker)
        }
      },
      // 获取工单列表
      getOrderList () {
        let data = AmapInfoWindow.data.filter((item, index) => index > (this.orderPage * 10) && index < ((this.orderPage + 1) * 10))
        this.orderList = data.map(item => {
          if (this.selectOrder.some(item2 => item2.orderId === item.orderId)) {
            item.checked = true
          } else {
            item.checked = false
          }
          return item
        })
        this.orderCount = AmapInfoWindow.count
      },

      changePage (page, name) {
        if (name === 'order') {
          this.orderPage = page - 1
          this.getOrderList()
        } else if (name === 'service') {
          this.servicePage = page - 1
          this.getServerList()
        }
      },
      // 根据地址获取地理编码
      getNowCode (address) {
        geocoder.getLocation('address', function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            console.log(result)
          }
        })
      },
      // 获取中心点的详细地址
      getNowAddress () {
        // 地理编码返回详细地址
        geocoder.getAddress(this.center, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            console.log(result.regeocode.formattedAddress)
            this.nowAddress = result.regeocode.formattedAddress
            this.openInfo(this.nowAddress)
            // 获得了有效的地址信息:
            // 即，result.regeocode.formattedAddress
          } else {
            // 获取地址失败

          }
        })
      },
      addd(){
        this.axios.get("person/listPerson ").then(function (response) {
          console.log(response.status)
          console.log(response.data)
        }).catch(function (error) {
          console.log(error)
        })
        let lnglats = [[118.120987, 24.482432], [118.130987, 24.483432], [118.140987, 24.456432], [118.150987, 24.486442]];
        for (var i = 0; i < lnglats.length; i++) {
          var lnglat = lnglats[i];
          // 创建点实例
          var marker = new AMap.Marker({
            position: new AMap.LngLat(lnglat[0], lnglat[1]),
            extData:{
              id:i+1
            }
          });

          markers.push(marker);
        }
        overlayGroups = new AMap.OverlayGroup(markers)
        map.add(overlayGroups);

        let targetMarker = this.getOneOverlay(1)
        let latLng = [118.120887, 24.482542]
        let lineArr = []
        let targetPosition = targetMarker.getPosition()
        lineArr.push([targetPosition.getLng(),targetPosition.getLat()])
        lineArr.push(latLng)
        targetMarker.moveAlong(lineArr, 200);
      },

      getOneOverlay(targetId){
        let targetMarker
        for(var i = 0; i < markers.length; i++){
          // 获取存在每个 extData 中的 id
          var id = markers[i].getExtData().id;

          if(id === targetId){
            targetMarker = markers[i];
            break;
          }
        }
        return targetMarker
      },

      loadErMap(){
        map.remove(satelliteLayer);
      },
      loadWeiMap(){
        map.add(satelliteLayer);
      },
      // 搜索详细地址
      seachAddress () {
        let _this = this
        this.searchKey = this.$refs.tipinput.value
        if (_this.searchKey === '') {
          _this.searchResult = ''
          return false
        }
        AMap.service(['AMap.PlaceSearch'], function () {
          // 关键字查询
          placeSearch.search(_this.searchKey, (status, result) => {
            console.log(result)
            if (result.info === 'OK') {
              let data = result.poiList.pois[0].location
              _this.searchResult = result.poiList.pois
              _this.center = [data.lng, data.lat]
              marker.setPosition(_this.center)
              map.panTo(_this.center)
              _this.getNowAddress()
              console.log(data)
              console.log(result)
            } else {
              _this.nowAddress = '未搜索到数据'
            }
          })
        })
      },
      // 显示信息窗体
      openInfo (address) {
        // let info = []
        // info.push('地址')
        // info.push(address)
        let infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)})
        infoWindow.setContent(address)
        infoWindow.open(map, this.center)
      },
      clickAddress (index) {
        console.log(index)
        this.center = [index.location.lng, index.location.lat]
        console.log(this.center)
        marker.setPosition(this.center)
        map.panTo(this.center)
        this.getNowAddress()
      }
    }
  }
</script>

<style>
  .AMap {
    margin: 0;
    padding: 0;
    height: calc(100% - 61px);
  }
  #container {
    width: 100%;
    height: 100%;
  }
  .input-card {
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    #background-color: rgba(255, 255, 255, 0);
    background-clip: border-box;
    border-radius: .25rem;
    width: 22rem;
    border-width: 0;
    border-radius: 0.4rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0);
    position: fixed;
    bottom: 1rem;
    right: 1rem;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 1.25rem;
  }

  .input-text {
    line-height: 2rem;
    margin-right: 2rem;
  }

  .info hr {
    margin-right: 0;
    margin-left: 0;
    border-top-color: grey;
  }

  .info {
    padding: .75rem 1.25rem;
    margin-bottom: 1rem;
    border-radius: .25rem;
    position: fixed;
    top: 1rem;
    background-color: white;
    width: auto;
    min-width: 22rem;
    border-width: 0;
    right: 1rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  }

  .code {
    left: 1.5rem;
    right: 1.5rem;
    top: 1.5rem;
    bottom: 1.5rem;
    overflow: auto;
    margin-bottom: 0rem;
  }

  .code .btn {
    top: 1rem;
    position: absolute;
    right: 1rem;
  }

  .code .result {
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 0.5rem;
    padding: 1rem;
    bottom: 1rem;
    position: absolute;
    top: 5.5rem;
    right: 1rem;
    left: 1rem;
    overflow: auto;
  }

  .code .status {
    color: #80adff;
    display: inline-block;
    font-size: 14px;
  }

  .code h4 {
    display: inline-block;
    max-width: 20rem;
    margin-right: 1rem;
    margin-bottom: 1rem;
  }

  select, input[type=text], input[type=date] {
    display: inline-block;
    width: 100%;
    padding: .375rem 1.75rem .375rem .75rem;
    line-height: 1.5;
    color: #495057;
    vertical-align: middle;
    background: #fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center;
    background-size: 8px 10px;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none
  }

  input[type=text],input[type=date] {
    background: #fff;
    padding: .375rem .75rem;
  }

  select:focus, input[type=text]:focus, input[type=date]:focus {
    border-color: #80bdff;
    outline: 0;
    box-shadow: 0 0 0 .1rem rgba(128, 189, 255, .1)
  }

  .btn:focus {
    outline: 0;
    box-shadow: none;
  }

  select:focus::-ms-value, input[type=text]:focus::-ms-value,input[type=date]:focus::-ms-value {
    color: #495057;
    background-color: #fff
  }


  /* native toastr */
  .native-toast {
    position: fixed;
    background-color: rgba(50, 50, 50, .8);
    border-radius: 33px;
    color: white;
    left: 50%;
    text-align: center;
    padding: 6px 12px;
    opacity: 0;
    z-index: 99999;
    transition: transform .25s, opacity .25s, top .25s;
    box-sizing: border-box;
  }

  .native-toast-bottom {
    bottom: 50px;
    -ms-transform: translateX(-50%) translateY(50px);
    transform: translateX(-50%) translateY(50px)
  }

  .native-toast-bottom.native-toast-shown {
    opacity: 1;
    -ms-transform: translateX(-50%) translateY(0);
    transform: translateX(-50%) translateY(0);
  }

  .native-toast-bottom.native-toast-edge {
    bottom: 0;
  }

  .native-toast-top {
    top: 50px;
    -ms-transform: translateX(-50%) translateY(-50px);
    transform: translateX(-50%) translateY(-50px)
  }

  .native-toast-top.native-toast-shown {
    opacity: 1;
    -ms-transform: translateX(-50%) translateY(0);
    transform: translateX(-50%) translateY(0);
  }

  .native-toast-top.native-toast-edge {
    top: 0;
  }

  .native-toast-center {
    top: 0;
    -ms-transform: translateX(-50%) translateY(-50px);
    transform: translateX(-50%) translateY(-50px)
  }

  .native-toast-center.native-toast-shown {
    opacity: 1;
    top: 50%;
    -ms-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
  }

  .native-toast-edge {
    border-radius: 0;
    width: 100%;
    text-align: left;
  }

  @media screen and (min-width: 40rem) {
    .native-toast:not(.native-toast-edge) {
      max-width: 18rem;
    }
  }

  /*
    max-width does not seem to work in small screen?
  */

  /*@media screen and (max-width: 768px) {
    .native-toast:not(.native-toast-edge) {
      max-width: 400px;
    }
  }

  @media screen and (max-width: 468px) {
    .native-toast:not(.native-toast-edge) {
      max-width: 300px;
    }
  }*/

  /* types */

  .native-toast-error {
    background-color: #d92727;
    color: white;
  }

  .native-toast-success {
    background-color: #62a465;
    color: white;
  }

  .native-toast-warning {
    background-color: #fdaf17;
    color: white;
  }

  .native-toast-info {
    background-color: #5060ba;
    color: white;
  }

  [class^="native-toast-icon-"] {
    vertical-align: middle;
    margin-right: 8px
  }

  [class^="native-toast-icon-"] svg {
    width: 16px;
    height: 16px;
  }

  .amap-detail {
    display: flex;
    height: calc(100%);
  }

  .amap-detail .left-body {
    transition: .5s;
    position: relative;
    box-shadow: 2px 1px 4px #EDEDED;
    height: calc(100%);
  }
  .amap-detail .left-position {
    position: absolute;
    right: -20px;
    top: 45%;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }

  .amap-detail .right-body {
    transition: .5s;
    position: relative;
    box-shadow: -2px 1px 4px #EDEDED;
  }
  .amap-detail .right-position {
    position: absolute;
    left: -20px;
    top: 45%;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }

  .amap-detail .left-show-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 20px;
    height: 35px;
    background: #3CCBA6;
    z-index: 2;
  // box-shadow: 2px 0 4px #EDEDED;
    color: #FFF;
    font-size: 12px;
    transition: .5s;
    cursor: pointer;
  }

  .amap-detail .amap-list-body {
    position: relative;
    width: 100%;
    max-height: 100%;
    height: calc(100%);
    flex-shrink: 0;
    overflow-x: hidden;
  }

  .amap-detail .order-list {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    height: 90px;
    width: 220px;
    line-height: 24px;
    padding-left: 15px;
    border-bottom: 1px solid #ededed;
  }

  .amap-detail .order-list .order-detail {
    overflow: hidden;
    flex: 1;
  }

  .amap-detail .order-list .title {
    font-size: 13px;
    color: #3ccba6;
  }

  .amap-detail .select-active {
    background: #F5F7F9
  }

  .amap-detail .amap-person-body {
    width: 100%;
    height: 100%;
    flex-shrink: 0;
  }

  .amap-detail .mymap {
    width: 100%;
    height: 522px;
    flex: 1;
  }

  .amap-detail .page-body {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    padding-top: 10px;
    padding-bottom: 10px;
    background: #fff;
    border-top: 1px solid #ededed;
    width: 100%;
    bottom: 0;
  }

  .amap-detail .amapTips {
    position: absolute;
    top: 10px;
    right: 10px;
    font-size: 12px;
    background-color: #fff;
    height: 35px;
    text-align: left;
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 3px;
    border: 1px solid #ccc;
    line-height: 30px;
    z-index: 999;
  }

  .amap-detail .smy__text-overflow-one-line {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
